package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.ResponseBean;
import com.android.infantschool.manager.BleManager;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.mvp.presenter.AddTemperaturePresenter;
import com.android.infantschool.model.mvp.presenter.AddTemperaturePresenterImpl;
import com.android.infantschool.model.mvp.view.AddTemperatureView;
import com.android.infantschool.ui.dialog.DialogConnectBle;
import com.android.infantschool.ui.dialog.DialogSignInSuccess;
import com.android.infantschool.util.ToastUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Administrator
 * @particulars
 * @time 2019\7\4 0004 14:40
 * @class describe
 */
public class ThermometryActivity extends BaseActivity implements DialogSignInSuccess.OnLister, AddTemperatureView {

    @BindView(R.id.tv_temperature)
    public TextView tvTemperature;
    @BindView(R.id.btn_submit)
    public Button btnSubmit;
    @BindView(R.id.title)
    public RelativeLayout rlTitle;
    @BindView(R.id.tv_title)
    public TextView tvTitle;

    @BindView(R.id.img_back)
    public ImageView imgBack;

    private BluetoothServerSocket mserverSocket = null;
    private ServerThread startServerThread = null;
    private clientThread clientConnectThread = null;
    private BluetoothSocket socket = null;
    private BluetoothDevice device = null;
    private readThread mreadThread = null;
    public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    private volatile boolean isBabyT = false;

    private String babyName = "";
    private String bleName = "";
    private String bleAddress;

    private AddTemperaturePresenter addTemperaturePresenter = null;

    public static Intent newIntent(Activity activity, String name, String address, String babyName, String babyId) {
        Intent intent = new Intent(activity, ThermometryActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("address", address);
        intent.putExtra("babyName", babyName);
        intent.putExtra("babyId", babyId);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thermometry);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        addTemperaturePresenter = new AddTemperaturePresenterImpl(this);

        babyName = getIntent().getStringExtra("babyName");
        rlTitle.setPadding(0, this.height, 0, 0);
        tvTitle.setText(babyName);
    }

    private DialogSignInSuccess dialogSignInSuccess = null;
    private DialogConnectBle dialogConnectBle = null;

    private void connectBle() {
        if (dialogConnectBle != null) {
            dialogConnectBle.dismiss();
            dialogConnectBle = null;
        }
        dialogConnectBle = new DialogConnectBle(this);
        dialogConnectBle.show();
    }

    private void dismissBle() {
        if (dialogConnectBle != null) {
            dialogConnectBle.dismiss();
            dialogConnectBle = null;
        }
    }

    @OnClick({R.id.btn_submit, R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                if (!isBabyT) {
                    ToastUtil.showShortToast(this, "请先测量体温");
                    return;
                }
                double data = Double.parseDouble(tvTemperature.getText().toString().substring(0, tvTemperature.getText().toString().length() - 1));
                if (data < 35.0 || data > 42.0) {
                    ToastUtil.showShortToast(this, "请量出正常体温");
                    return;
                }
                this.showLoading();
                Map<String, String> map = new HashMap<>();
                map.put("token", AppConfig.getToken());
                map.put("id", getIntent().getStringExtra("babyId"));
                map.put("temperature", String.valueOf(data));
                map.put("type", "1");//1宝宝测温2签到
                Log.e(TAG, "map:" + map.toString());
                addTemperaturePresenter.postAddTemperature(map);
                break;
            case R.id.img_back:
                this.finish();
                break;
        }
    }

    @Override
    public void lister() {
        if (dialogSignInSuccess != null) {
            dialogSignInSuccess.dismiss();
            dialogSignInSuccess = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        connectBle();
        Log.e(TAG, "address:" + getIntent().getStringExtra("address"));
        BleManager.serviceOrCilent = BleManager.ServerOrCilent.CILENT;
        if (BleManager.isOpen) {
            dismissBle();
            return;
        }
        if (BleManager.serviceOrCilent == BleManager.ServerOrCilent.CILENT) {
            String address = getIntent().getStringExtra("address");
            if (!address.equals("null")) {
                device = mBluetoothAdapter.getRemoteDevice(address);
                clientConnectThread = new clientThread();
                clientConnectThread.start();
                BleManager.isOpen = true;
                dismissBle();
            } else {
                Toast.makeText(this, "未找到蓝牙设备", Toast.LENGTH_SHORT).show();
                BleManager.isOpen = false;
                dismissBle();
            }
        } else if (BleManager.serviceOrCilent == BleManager.ServerOrCilent.SERVICE) {
            startServerThread = new ServerThread();
            startServerThread.start();
            BleManager.isOpen = true;
            dismissBle();
        }
    }

    @Override
    public void errorAddTemperature(String error) {
        this.dismissLoading();
        ToastUtil.showLongToast(this, "网络异常:" + error);
    }

    @Override
    public void successAddTemperature(BaseBean baseBean) {
        this.dismissLoading();
        ResponseBean infoBean = (ResponseBean) baseBean;
        if (infoBean.getCode() == 0) {
            ToastUtil.showLongToast(this, "提交成功");
            this.finish();
        } else {
            ToastUtil.showLongToast(this, "提交失败:" + infoBean.getMsg());
        }
    }

    //开启客户端
    private class clientThread extends Thread {
        public void run() {
            try {
                SystemClock.sleep(300);
                //创建一个Socket连接：只需要服务器在注册时的UUID号
                // socket = device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);
                socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                Log.e(TAG, "请稍候，正在连接服务器:" + getIntent().getStringExtra("address"));
                socket.connect();
                Log.e(TAG, "已经连接上服务端!");
                //启动接受数据
                mreadThread = new readThread();
                mreadThread.start();
                Log.e(TAG, "连接成功");
                BleManager.isOpen = true;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTemperature.setText("连接成功,可测体温!");
                    }
                });
            } catch (IOException e) {
                Log.e(TAG, "连接断开:" + e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTemperature.setText("连接失败,请退出重新连接测量!");
                    }
                });
                BleManager.isOpen = false;
            }
        }
    }

    //开启服务器
    private class ServerThread extends Thread {
        public void run() {
            try {
                /* 创建一个蓝牙服务器
                 * 参数分别：服务器名称、UUID	 */
                mserverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
                        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                Log.e(TAG, "请稍候，正在等待客户端的连接...");
                /* 接受客户端的连接请求 */
                socket = mserverSocket.accept();
                Log.e(TAG, "客户端已经连接上,可以发送信息.");
                //启动接受数据
                mreadThread = new readThread();
                mreadThread.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e(TAG, "连接失败" + e.toString());
            }
        }
    }

    /* 停止服务器 */
    private void shutdownServer() {
        new Thread() {
            public void run() {
                if (startServerThread != null) {
                    startServerThread.interrupt();
                    startServerThread = null;
                }
                if (mreadThread != null) {
                    mreadThread.interrupt();
                    mreadThread = null;
                }
                try {
                    if (socket != null) {
                        socket.close();
                        socket = null;
                    }
                    if (mserverSocket != null) {
                        mserverSocket.close();/* 关闭服务器 */
                        mserverSocket = null;
                    }
                } catch (IOException | NullPointerException e) {
                    Log.e("server", "mserverSocket.close()", e);
                }
            }
        }.start();
    }

    /* 停止客户端连接 */
    private void shutdownClient() {
        new Thread() {
            public void run() {
                if (clientConnectThread != null) {
                    clientConnectThread.interrupt();
                    clientConnectThread = null;
                }
                if (mreadThread != null) {
                    mreadThread.interrupt();
                    mreadThread = null;
                }
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    socket = null;
                }
            }
        }.start();
    }

    /**
     * java字节码转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) { //一个字节的数，
        // 转成16进制字符串
        String hs = "";
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            //整数转成十六进制表示
            tmp = (Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                hs = hs + "0" + tmp;
            } else {
                hs = hs + tmp;
            }
        }
        return hs.toUpperCase(); //转成大写
    }

    //读取数据
    private class readThread extends Thread {
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            InputStream mmInStream = null;
            try {
                mmInStream = socket.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            while (true) {
                try {
                    if ((bytes = mmInStream.read(buffer)) > 0) {
                        byte[] buf_data = new byte[bytes];
                        for (int i = 0; i < bytes; i++) {
                            buf_data[i] = buffer[i];
                        }
                        String s = new String(byte2hex(buf_data));
                        final float wendu = Integer.parseInt(s.substring(2, 6), 16) / 10.0f;
                        Log.e(TAG, "接收到的蓝牙枪数据:" + wendu);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvTemperature.setText(wendu + "°");
                                isBabyT = true;
                            }
                        });
                    }
                } catch (IOException e) {
                    try {
                        mmInStream.close();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    break;
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        shutdownClient();
        shutdownServer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isBabyT = false;
        BleManager.isOpen = false;
        if (addTemperaturePresenter != null) {
            addTemperaturePresenter.onDestroy();
            addTemperaturePresenter = null;
        }
    }
}